﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.UI.Mediasend.Logic;
using Telerik.Web.UI;
using Medianamik.Globalization;
using Medianamik.Core;

namespace Medianamik.UI.Mediasend
{
    /// <summary>
    /// Page servant à faire un envoi Mediasend
    /// </summary>
    public partial class newsletterConfiguration : BasePage
    {
        private MediasendUserControl _currentControl;
        public bool GlobalErrorOccured;

        /// <summary>
        /// Données du mailing courrant
        /// </summary>
        public MailingDataShell Data
        {
            get
            {
                return (MailingDataShell)(ViewState["data"] ?? (ViewState["data"] = new MailingDataShell()));
            }
            set { ViewState["data"] = value; }
        }

        /// <summary>
        /// Dernier step accédé.
        /// </summary>
        protected int LastStepEntered
        {
            get { return (int)(ViewState["LastStepEntered"] ?? (ViewState["LastStepEntered"] = 0)); }
            set { ViewState["LastStepEntered"] = value; }
        }

        public string GlobalError
        {
            get { return lblGlobalError.Text; }
            set
            {
                lblGlobalError.Text = value;
                if (value != "")
                {
                    GlobalErrorOccured = true;
                    //Erreur global présente alors, on désactive l'interface
                    wizNewsletter.Visible = false;
                    tabNavigation.Visible = false;
                }

            }
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            ((BaseMasterPage)Master).RemoveLanguagePicker = true;
        }

        /// <summary>
        /// Attacher les événements du Wizard
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            if (Configuration.Instance.Properties.BaseNodeTemplateNode == null || Configuration.Instance.Properties.Username.IsNullOrEmpty() || Configuration.Instance.Properties.Password.IsNullOrEmpty())
                GlobalError = Translator.Translate("Medianamik_Mediasend", "Error_SetBaseMediasendConfig");

            wizNewsletter.NextButtonClick += wizNewsletter_ButtonClick;
            //Nous ne voulons pas de sauvegarde au previous.
            //wizNewsletter.PreviousButtonClick += wizNewsletter_ButtonClick;            
            wizNewsletter.ActiveStepChanged += wizNewsletter_ActiveStepChanged;
        }

        /// <summary>
        /// Dès que l'envoi est terminé, on ne doit pas permettre à la personne de revenir en arrière
        /// </summary>
        void Data_OnSent()
        {
            tabNavigation.Enabled = false;

            var buttonPrevious = wizNewsletter.FindControlR("FinishPreviousButton") as WebControl;
            if (buttonPrevious != null)
                buttonPrevious.Enabled = false;

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SetCurrentControl();
            if (!IsPostBack)
            {
                BindNavigation();
            }
            else
            {
                if (EditionCultureHasChanged)
                    FireCultureChangedEvent();
            }
            Data.OnSent += Data_OnSent;

            //On doit enlever le bouton Complete car aucune utilisé.
            var completeButton = wizNewsletter.FindControlR("FinishButton") as WebControl;
            if (completeButton != null)
                completeButton.Parent.Controls.Remove(completeButton);
        }

        /// <summary>
        /// Construction de la navigation
        /// </summary>
        private void BindNavigation()
        {
            var steps = new List<int>();
            
            for (var i=1; i <= wizNewsletter.WizardSteps.Count; i++)
                steps.Add(i);

            
            tabNavigation.DataSource = steps;
            tabNavigation.DataBind();
            tabNavigation.SelectedIndex = wizNewsletter.ActiveStepIndex;

            foreach (RadTab tab in tabNavigation.Tabs)
            {
                tab.Enabled = tab.Index <= LastStepEntered;
            }
        }

        /// <summary>
        /// lorsqu'on clique sur un élément de la navigation, on change de step
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tabNavigation_Clicked(object sender, RadTabStripEventArgs e)
        {
            if (_currentControl.Save())
            {
                var index = e.Tab.Index;
                wizNewsletter.ActiveStepIndex = index;
                tabNavigation.SelectedIndex = index;
            }
        }

        /// <summary>
        /// Changement du contrôle acutel vue le changement d'étape
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wizNewsletter_ActiveStepChanged(object sender, EventArgs e)
        {
            SetCurrentControl();
            _currentControl.SetControls();
            LastStepEntered = wizNewsletter.ActiveStepIndex > LastStepEntered
                                  ? wizNewsletter.ActiveStepIndex
                                  : LastStepEntered;

            BindNavigation();
        }

        /// <summary>
        /// Chaque fois que nous changeons d'étape, il faut demander au control actuel de
        /// se sauvegarder.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void wizNewsletter_ButtonClick(object sender, WizardNavigationEventArgs e)
        {
            e.Cancel = !_currentControl.Save();
        }

        private void SetCurrentControl()
        {
            if (wizNewsletter.ActiveStep != null && !GlobalErrorOccured)
                _currentControl = wizNewsletter.ActiveStep.Controls.OfType<MediasendUserControl>().First();
        }

        /// <summary>
        /// Au changement de langue, on rafraichi les controles.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnCultureChanged(CultureChangedEventArgs e)
        {
            _currentControl.OnChangeCulture();
        }
    }
}
